<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>函数作为值</title>
</head>

<body>
  <script>
    // function square(x) {
    //   return x * x
    // }
    // let s = square
    // console.log(s(4));
    // console.log(square(4));

    // 实例
    function add(x, y) {
      return x + y
    }
    function subtract(x, y) {
      return x - y
    }
    function multiply(x, y) {
      return x * y
    }
    function divide(x, y) {
      return x / y
    }
    function operate(operator, operand1, operand2) {
      return operator(operand1, operand2)
    }

    let i = operate(add, operate(add, 2, 3), operate(multiply, 4, 5))
    console.log(i);


    const operators = {
      add: (x, y) => x + y,
      subtract: (x, y) => x - y,
      multiply: (x, y) => x * y,
      divide: (x, y) => x / y,
      pow: Math.pow
    }

    function operate2(operation, operand1, operand2) {
      if (typeof operators[operation] === "function") {
        return operators[operation](operand1, operand2)
      }
      else throw "unknown operator"
    }
    let p = operate2("add", "hello", operate2("add", " ", "world"))
    console.log(p);
    console.log(operate2("pow", 10, 2));


    // 定义自己的函数属性
    function factorial(n) {
      if (Number.isInteger(n) && n > 0) {
        if (!(n in factorial)) {
          factorial[n] = n * factorial(n - 1)
        }
        return factorial[n]
      } else {
        return NaN
      }
    }
    factorial[1] = 1
    console.log(factorial(3));// factorial[3] =3*factorial(2)=3*2=6
    console.log(factorial[2]);
    console.log();
  </script>
</body>

</html>